package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.CustomException;
import com.itheima.ydd.dto.PageDto;
import com.itheima.ydd.dto.SysMenuDto;
import com.itheima.ydd.dto.SysRoleDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysRoleMenu;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.mapper.SysMenuMapper;
import com.itheima.ydd.mapper.SysRoleMapper;
import com.itheima.ydd.service.ISysRoleMenuService;
import com.itheima.ydd.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.service.ISysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysRoleMenuService roleMenuService;

    @Autowired
    private SysMenuMapper menuMapper;
    @Autowired
    private ISysUserService userService;

    /**
     * 分页
     *
     * @param name
     * @param page
     * @param limit
     * @return
     */
    @Override
    public PageDto getList(String name, int page, int limit) {

        Page<SysRole> sysRolePage = new Page<>();
        LambdaQueryWrapper<SysRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.like(StringUtils.isNotEmpty(name), SysRole::getName, name);
        // roleLambdaQueryWrapper.eq(SysRole::getDelFlag,"0");
        roleLambdaQueryWrapper.orderByDesc(SysRole::getCreateDate);
        this.page(sysRolePage, roleLambdaQueryWrapper);

        PageDto pageDto = new PageDto();
        BeanUtils.copyProperties(sysRolePage, pageDto);
        return pageDto;
    }

    /**
     * 新增
     *
     * @param map
     */
    @Transactional
    public void add(Map<String, Object> map) {
        String name = (String) map.get("name");
        String description = (String) map.get("description");
        List<Integer> menuIds = (List<Integer>) map.get("menuids");

        //添加角色前判断是否重复
        LambdaQueryWrapper<SysRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(SysRole::getName, name);
        SysRole sysRole = roleService.getOne(roleLambdaQueryWrapper);
        if (sysRole != null) {
            throw new CustomException("角色已存在");
        }
        //添加基本数据
        SysRole role = new SysRole();
        /*long roleId = IdWorker.getId();//生成订单号
        role.setId(String.valueOf(roleId));*/
        role.setName(name);
        role.setDescription(description);
        role.setDefaultData("1");
        role.setCreateDate(LocalDateTime.now());
        this.save(role);
        String id = role.getId();
        //添加关联数据
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        for (Integer menuId : menuIds) {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(String.valueOf(menuId));
            sysRoleMenus.add(roleMenu);
        }

        roleMenuService.saveBatch(sysRoleMenus);
    }


    /**
     * 修改回显
     *
     * @param roleId
     * @return
     */
    @Override
    public SysRoleDto rowInfo(String roleId) {
        //先查询角色基本数据
        SysRole sysRole = roleService.getById(roleId);
        SysRoleDto roleDto = new SysRoleDto();
        BeanUtils.copyProperties(sysRole, roleDto);


        List<SysMenu> menuList = menuMapper.selectMenu(roleId, 0);

        List<SysMenuDto> sysMenuDtos = menuList.stream().map(menu -> {
            SysMenuDto sysMenuDto = new SysMenuDto();
            BeanUtils.copyProperties(menu, sysMenuDto);

            this.getMenuDto(roleId, sysMenuDto);
            return sysMenuDto;
        }).collect(Collectors.toList());
        roleDto.setAuthList(sysMenuDtos);
        return roleDto;

    }

    /**
     * 修改
     *
     * @param sysRoleDto
     */
    @Transactional
    public void updateRole(SysRoleDto sysRoleDto) {
        //先修改基本数据
        this.updateById(sysRoleDto);
        //先删除原来角色关联信息
        List<String> menuids = sysRoleDto.getMenuids();
        LambdaQueryWrapper<SysRoleMenu> roleMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleMenuLambdaQueryWrapper.eq(SysRoleMenu::getRoleId, sysRoleDto.getId());
        roleMenuService.remove(roleMenuLambdaQueryWrapper);

        //在添加页面传传过来的要修改的数据

        List<SysRoleMenu> sysRoleMenus = menuids.stream().map(menuId -> {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(sysRoleDto.getId());
            return roleMenu;
        }).collect(Collectors.toList());
        roleMenuService.saveBatch(sysRoleMenus);
    }

    @Transactional
    public void del(String id) {
        //判断角色是否在使用
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getRoleId, "[\"" + id + "\"]");
        if (userService.count(wrapper) > 0) {
            throw new CustomException("该角色下有用户在使用,无法删除!");
        }
        //进行删除
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getId,id);
        roleService.remove(queryWrapper);
    }


    /**
     * 递归查询
     *
     * @param roleId
     * @param sysMenuDto
     */
    private void getMenuDto(String roleId, SysMenuDto sysMenuDto) {
        Integer id = sysMenuDto.getId();
        List<SysMenu> sysMenus = menuMapper.selectMenu(roleId, id);
        if (sysMenus.isEmpty()) {
            return;
        }
        List<SysMenuDto> sysMenuDtos = sysMenus.stream().map(menu -> {
            SysMenuDto dto = new SysMenuDto();
            BeanUtils.copyProperties(menu, dto);
            getMenuDto(roleId, dto);
            return dto;
        }).collect(Collectors.toList());
        sysMenuDto.setChildren(sysMenuDtos);

    }

}
